package tt.dz.egobus.servicemanager.business.task;

import tt.dz.egobus.api.ResponseBack;
import tt.dz.egobus.api.apushservice.PushVo;
import tt.dz.egobus.servicemanager.facade.driver.DriverFacade;

/**
 * @author Anson
 * @date 17-8-10
 * @name 推单异步服务任务
 * @since 1.0.6
 */
public class PushTaskRunnable implements Runnable {

    /**
     * 每次尝试的间隔为10秒
     */
    private static final int TRY_PRE_WAIT_TIME = 10 * 1000;

    /**
     * 失败之后,尝试次数,默认两次
     */
    private static final int TRY_TIMES = 2;

    private final DriverFacade driverFacade;
    private final PushTask pushTask;

    public PushTaskRunnable(DriverFacade driverFacade, PushTask pushTask) {
        this.driverFacade = driverFacade;
        this.pushTask = pushTask;
    }

    @Override
    public void run() {
        if (pushTask == null || pushTask.vo == null) {
            return;
        }
        ResponseBack<Boolean> isSuccess = this.handler();
        if (isMaybeRetry(isSuccess)) {
            //发送失败的时候
            int times = TRY_TIMES;
            int waitPreTime = TRY_PRE_WAIT_TIME;
            while (times > 0 && isMaybeRetry(isSuccess)) {
                isSuccess = this.handler();
                times--;
                try {
                    Thread.sleep(waitPreTime);
                } catch (InterruptedException e) {

                }
            }
        }
    }

    /**
     * @param isSuccess 当前操作值
     * @author Anson
     * @date 17-8-10
     * @name 根据当前结果判断是否需要重新尝试
     * @since 1.0.6
     */
    private boolean isMaybeRetry(ResponseBack<Boolean> isSuccess) {
        return !(isSuccess.isSuccess() && isSuccess.getResult());
    }

    protected ResponseBack<Boolean> handler() {
        ResponseBack<Boolean> isSuccess = ResponseBack.success(false);
        int type = pushTask.type;
        switch (type) {
            case 1:
                //司机端
                if (this.driverFacade == null) {
                    return isSuccess;
                }
                isSuccess = this.driverFacade.pushMessage(pushTask.vo);
                break;
            case 2:
                //用户端
                if (this.driverFacade == null) {
                    return isSuccess;
                }
                isSuccess = this.driverFacade.pushMessage(pushTask.vo);
                break;
        }
        return isSuccess;
    }


    public static class PushTask {
        //推单详细信息
        private PushVo vo;
        //当前用户类别,1司机,2用户
        private int type;

        public PushTask(PushVo vo, int type) {
            this.vo = vo;
            this.type = type;
        }

        public PushVo getVo() {
            return vo;
        }

        public void setVo(PushVo vo) {
            this.vo = vo;
        }

        public int getType() {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }
    }
}
